#include "lib.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include "log.h"

/**
 * @brief   路径处理
 * @param   ParaPath    参数描述
 * @param   TargetPath  参数描述
 * @param   flag        1表示遇到'\'需要进行增加一个'\'处理, 0表示不需要处理
 * @return  int
 * @date    2024-08-22
 *
 */
int FileNameHandle(char *ParaPath, char *TargetPath, int flag)
{
    char *CurrentPath;
    int i = 0, j = 0, k = 0;
    int PathLevel = 0, PathLast = 0;

    // 获取传入的参数路径有多少个上级目录,也就是"..\"的个数
    for (i = 0; (ParaPath[i] == '\\') || (ParaPath[i] == '.'); i++)
    {
        if ((ParaPath[i] == '.') && (ParaPath[i - 1] == '.'))
        {
            PathLevel++;
        }
    }
    // LOG_info("ParaPath:%s\n",ParaPath);
    // LOG_info("PathLevel:%d  i is:%d\n",PathLevel,i);

    // 获取当前绝对路径
    if ((CurrentPath = getcwd(NULL, 0)) == NULL)
    {
        perror("getcwd error");
    }
    // LOG_info("CurrentPath: %s\n",CurrentPath);

    // 当前绝对路径字符串由后往前遍历,根据上级目录个数PathLevel,去掉多余路径,得到参数路径的绝对路径
    for (i = strlen(CurrentPath) - 1; PathLast < PathLevel; i--)
    {
        if (CurrentPath[i] == '\\')
        {
            PathLast++;
        }
    }
    // LOG_info("PathLast:%d  i is:%d\n",PathLast,i);

    // 将处理后的当前绝对路径,赋值到目标路径的前面
    for (j = 0, k = 0; j <= i; j++)
    {
        TargetPath[k++] = CurrentPath[j];
        if (flag)
            if (CurrentPath[j] == '\\')
                TargetPath[k++] = '\\';
    }
    TargetPath[k] = '\0';
    // LOG_info("TargetPath:%s\n",TargetPath);

    for (i = 0; ParaPath[i] != '\0'; i++)
    {
        if (ParaPath[i] != '.')
        {
            TargetPath[k++] = ParaPath[i];
            if (flag)
                if (ParaPath[i] == '\\')
                    TargetPath[k++] = ParaPath[i];
        }
        if ((ParaPath[i] == '.') && ((ParaPath[i - 1] != '.') && (ParaPath[i + 1] != '.')))
            TargetPath[k++] = ParaPath[i];
    }
    TargetPath[k] = '\0';

    // LOG_info("TargetPath:%s\n",TargetPath);
    free(CurrentPath);
    return k;
}

const char VersionRc[][16] = {"Base", "Alpha", "Beta", "RC", "Release", "standard", "full", "lts", "ultimate", "demo", "enhance", "free", "upgrade"};

/**
 * @brief   获取版本号
 * @param   filename    参数描述
 * @return  uint32_t
 * @date    2024-08-25
 *
 */
uint32_t GetIniVersionString(const char *filename)
{
    FILE *fp;
    char sLine[1024];
    char sLine1[1024];
    char word1[32], rc[32];
    char NAME[1024];
    int main = 0, sub1 = 0, sub2 = 0, i = 0, rv = 0;
    if (NULL == (fp = fopen(filename, "r")))
    {
        LOG_error("open %s failed.\n", filename);
        return 0;
    }

    while (NULL != fgets(sLine, 1024, fp))
    {

        switch (i)
        {
        case 0:
            if (!strstr(sLine, "PROJECT_NAME"))
            {
                continue;
            }
            sscanf(sLine, "%s %s \"%s", word1, word1, word1);
            strcpy(NAME, strtok(word1, "\""));
            i++;
            fseek(fp, 0, SEEK_SET);
            break;

        case 1:
            if (!strstr(sLine, "APP_VERSION_MAIN"))
            {
                continue;
            }
            sscanf(sLine, "%s %s %[^1-9]%d", word1, word1, word1, &main);
            i++;
            fseek(fp, 0, SEEK_SET);
            break;

        case 2:
            if (!strstr(sLine, "APP_VERSION_SUB1"))
            {
                continue;
            }
            sscanf(sLine, "%s %s %[^1-9]%d", word1, word1, word1, &sub1);
            i++;
            fseek(fp, 0, SEEK_SET);
            break;
        case 3:
            if (!strstr(sLine, "APP_VERSION_SUB2"))
            {
                continue;
            }
            sscanf(sLine, "%s %s %[^1-9]%d", word1, word1, word1, &sub2);
            i++;
            fseek(fp, 0, SEEK_SET);
            break;

        case 4:
            if (!strstr(sLine, "APP_VERSION_RC"))
            {
                continue;
            }
            sscanf(sLine, "%s %s (%[^)]", word1, word1, rc);
            /*获取RC版本类型编号*/
            for (size_t i = sizeof(VersionRc) / sizeof(VersionRc[0]); i > 0; i--)
            {
                size_t a = 0;
                a = i - 1;
                if (strstr(rc, VersionRc[a]))
                {
                    rv = a;
                    break;
                }
                if (i == 1)
                {
                    LOG_error("APP_VERSION_RC error:%s", rc);
                    LOG_info("%s", sLine);
                }
            }

            /*获取当前时间戳*/
            time_t now = time(NULL);
            if (now == (time_t)-1)
            {
                LOG_error("Failed to get current time.");
                return 0;
            }

            /*将时间戳转换为本地时间结构*/
            struct tm *tm = localtime(&now);
            if (tm == NULL)
            {
                LOG_error("Failed to convert time to local time.");
                return 0;
            }

            /*定义缓冲区存储格式化后的日期字符串*/
            char buf[9]; // YYYYMMDD + '\0'
            if (strftime(buf, sizeof(buf), "%Y%m%d", tm) == 0)
            {
                LOG_error("Failed to format date string.");
                return 0;
            }

            LOG_info("%s_V%d.%d.%d.%s_%s", NAME, main, sub1, sub2, buf, rc);
            fclose(fp);
            return (main << 24) | (sub1 << 16) | (sub2 << 8) | rv;
            break;

        default:
            break;
        }
    }
}


 /**
  * @brief   获取工程名称
  * @param   filename        所在文件目录
  * @param   projectName     缓存
  * @param   projectNameSize 长度
  * @return  char* 
  * @date    2025-03-15
  * 
  */
char *GetProjectNameString(const char *filename, char *projectName, size_t projectNameSize)
{
    FILE *fp;
    char sLine[1024];
    char word1[32];

    // 清空 projectName 缓冲区
    memset(projectName, 0, projectNameSize);

    if (NULL == (fp = fopen(filename, "r")))
    {
        LOG_error("open %s failed.\n", filename);
        return NULL;
    }

    while (NULL != fgets(sLine, sizeof(sLine), fp))
    {
        if (!strstr(sLine, "PROJECT_NAME"))
        {
            continue;
        }
        sscanf(sLine, "%s %s \"%[^\"]\"", word1, word1, word1);

        // LOG_info("%d", strlen(word1)>projectNameSize?projectNameSize:strlen(word1));
        strncpy(projectName, word1, strlen(word1)>projectNameSize?projectNameSize:strlen(word1));
        fclose(fp);
        return projectName;
    }

    fclose(fp);
    return NULL; // 如果未找到 PROJECT_NAME，返回 NULL
}